package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivityApplySmsDataBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomProcessHelper

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/25 18:45
 * @Annotation：申请贷款等待
 */
class ActivityApplySmsData: ShipweActivity() {
    lateinit var binding: ActivityApplySmsDataBinding
    //等待时长
    private var countdown = 9
    private var countdownTimer: MyCountDownTimer? = null

    var eventRemark = ""
    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, ActivityApplySmsData::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getShipweRootView(): View {
        binding = ActivityApplySmsDataBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnVisibility(View.INVISIBLE)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitleVisibility(View.GONE)

        val textSMS = getString(R.string.loan_apply_wait_sms)
        val showText = String.format(getString(R.string.loan_apply_wait_tips),textSMS)

        val smsIndex = showText.indexOf(textSMS)
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF4D3E")), smsIndex, smsIndex + textSMS.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(StyleSpan(Typeface.BOLD), smsIndex, smsIndex + textSMS.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.applySmsDataWaitTips.text = spString
    }

    override fun initShipweListener() {
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark,getProductName(),getProductToken())
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,eventRemark)
        }
    }

    override fun initShipweData() {
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, 9000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: ActivityApplySmsData,millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showApplySmsDataTipsText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showApplySmsDataComplete()
        }
    }

    /**
     * 设置文本
     */
    @SuppressLint("SetTextI18n")
    private fun showApplySmsDataTipsText(){
        binding.applySmsDataCountdown.text = "${countdown}s"
        showApplySmsDataStepStatusView()
    }

    /**
     * 贷款订单创建成功
     */
    private fun showApplySmsDataComplete(){
        showShipweLoading()
        //刷新主流程
        publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PROCESS_REFRESH))
    }

    /**
     *旋转动画
     */
    private fun getApplySmsDataAnimation(): Animation {
        // 创建一个旋转动画对象，从当前的角度旋转到指定的角度，持续时间为1000毫秒
        val rotateAnimation = RotateAnimation(0F, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        rotateAnimation.setDuration(1000L) // 设置动画持续时间
//        rotateAnimation.fillAfter = false // 动画执行完后保持结束状态
        rotateAnimation.isFillEnabled = true;
        rotateAnimation.fillBefore = false;
        rotateAnimation.setRepeatCount(Animation.INFINITE); // 设置动画重复次数
        return rotateAnimation
    }

    /**
     * 显示状态
     */
    private fun showApplySmsDataStepStatusView(){
        if (countdown in 7..9){
            binding.applySmsDataStep1.setImageResource(R.drawable.wait_progress_icon)
            binding.applySmsDataStep1Text.setTextColor(Color.parseColor("#FF000000"))
            binding.applySmsDataStep1.startAnimation(getApplySmsDataAnimation())

            binding.applySmsDataStep2.setImageResource(R.drawable.wait_countdown_icon)
            binding.applySmsDataStep2Text.setTextColor(Color.parseColor("#FF88888B"))

            binding.applySmsDataStep3.setImageResource(R.drawable.wait_countdown_icon)
            binding.applySmsDataStep3Text.setTextColor(Color.parseColor("#FF88888B"))
            return
        }

        if (countdown in 4..6){
            binding.applySmsDataStep1.setImageResource(R.drawable.select_theme)
            binding.applySmsDataStep1Text.setTextColor(Color.parseColor("#FF88888B"))
            binding.applySmsDataStep1.clearAnimation()

            binding.applySmsDataStep2.setImageResource(R.drawable.wait_progress_icon)
            binding.applySmsDataStep2Text.setTextColor(Color.parseColor("#FF000000"))
            binding.applySmsDataStep2.startAnimation(getApplySmsDataAnimation())

            binding.applySmsDataStep3.setImageResource(R.drawable.wait_countdown_icon)
            binding.applySmsDataStep3Text.setTextColor(Color.parseColor("#FF88888B"))
            return
        }
        binding.applySmsDataStep1.setImageResource(R.drawable.select_theme)
        binding.applySmsDataStep1Text.setTextColor(Color.parseColor("#FF88888B"))
        binding.applySmsDataStep1.clearAnimation()

        binding.applySmsDataStep2.setImageResource(R.drawable.select_theme)
        binding.applySmsDataStep2Text.setTextColor(Color.parseColor("#FF88888B"))
        binding.applySmsDataStep2.clearAnimation()

        if (countdown >= 2){
            binding.applySmsDataStep3.setImageResource(R.drawable.wait_progress_icon)
            binding.applySmsDataStep3Text.setTextColor(Color.parseColor("#FF000000"))
            binding.applySmsDataStep3.startAnimation(getApplySmsDataAnimation())
            return
        }
        binding.applySmsDataStep3.setImageResource(R.drawable.select_theme)
        binding.applySmsDataStep3Text.setTextColor(Color.parseColor("#FF88888B"))
        binding.applySmsDataStep3.clearAnimation()
    }

    /**
     * 获取查看的产品名称
     */
    private fun getProductName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    private fun getProductToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        when(event.eventType){
            AppEventData.TYPE.SHIPWE_PROCESS_REFRESHED -> {
                dismissShipweLoading()
                //需要校验 WhatsApp 或 SMS
                if (CustomProcessHelper.isCheckWhatsApp() || CustomProcessHelper.isCheckSMS()){
                    ActivityCheckNumber.start(this,getProductName(),getProductToken())
                } else {
                    val pName = getProductName()
                    val pToken = getProductToken()
                    ActivityOrderDetails.start(this, pName, pToken)
                }
                finish()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${getProductName()} Loan SMS Preview Page"
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_SMS_PREVIEW_START, eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_SMS_PREVIEW_END, eventRemark)
        if (countdownTimer != null){
            countdownTimer = null
        }
    }
}